﻿using RuoVea.SM.SMExtend;
using System;
using System.Text;
namespace RuoVea.SM;

/// <summary>
/// SM3国密哈希算法工具类
/// 提供SM3哈希计算功能
/// </summary>
public class SM3Crypt
{
    /// <summary>
    /// 计算SM3哈希值
    /// </summary>
    /// <param name="data">要哈希的数据</param>
    /// <returns>64字符的16进制哈希字符串</returns>
    /// <exception cref="ArgumentNullException">输入数据为空</exception>
    public static string Encrypt(string data)
    {
        if (string.IsNullOrEmpty(data))
            throw new ArgumentNullException(nameof(data));

        byte[] inputBytes = Encoding.UTF8.GetBytes(data);
        byte[] hashBytes = ComputeSm3(inputBytes);

        return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
    }

    /// <summary>
    /// 计算SM3哈希
    /// </summary>
    private static byte[] ComputeSm3(byte[] data)
    {
        var sm3 = new SM3Digest();
        sm3.BlockUpdate(data, 0, data.Length);
        byte[] result = new byte[sm3.GetDigestSize()];
        sm3.DoFinal(result, 0);
        return result;
    }
     
    /// <summary>
    /// 验证哈希值是否匹配
    /// </summary>
    public static bool Verify(string data, string hash)
    {
        string computedHash = Encrypt(data);
        return string.Equals(computedHash, hash, StringComparison.OrdinalIgnoreCase);
    }
}